package cn.com.lyj6851.user.controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.com.lyj6851.common.util.BeanValidator;
import cn.com.lyj6851.user.entity.SysUser;
import cn.com.lyj6851.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 〈功能简述〉<br>
 * 〈用户controller〉
 *
 */
@RestController
@Api(tags = "用户Controller")
public class UserController {

	@Autowired
	PasswordEncoder passwordEncoder;
	
	@Autowired
    UserService userService;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@GetMapping("users")
    @ApiOperation(value = "查询所有用户")
    public ResponseEntity<List<SysUser>> findAll(SysUser user) {
        return ResponseEntity.ok(user.selectList(new QueryWrapper(user)));
    }
	
	@GetMapping("users/{username}")
    @ApiOperation(value = "通过用户名查询用户")
    public ResponseEntity<SysUser>  findByUsername(@PathVariable("username") String username){
		
        return ResponseEntity.ok(userService.getOne(new QueryWrapper<>(new SysUser()).eq("username",username)));
    }

	@PostMapping("user")
    @ApiOperation(value = "新增")
    public BodyBuilder add(SysUser user) {
		BeanValidator.check(user);
        user.setId(UUID.randomUUID().toString());
        user.setStatus("0");
        user.setCreateTime(new Date());
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.insert();
        return ResponseEntity.ok();
    }
	
	@DeleteMapping("user")
    @ApiOperation(value = "删除用户")
    public BodyBuilder delete(SysUser user) {
        user.deleteById();
        return ResponseEntity.ok();
    }

    @PutMapping("user")
    @ApiOperation(value = "修改用户")
    public BodyBuilder update(SysUser user){
    	BeanValidator.check(user);
        user.updateById();
        return ResponseEntity.ok();
    }
}
